<template>
  <div class="app-container calendar-list-container">
   <div class="filter-container">
     <el-select  style="width: 140px" class="filter-item" v-model="search.status" placeholder="状态搜索" >
        <el-option label="全部" value=''></el-option> <!--2:维护,1正常,3:作废-->
        <el-option label="正常" value='1'></el-option> <!--2:维护,1正常,3:作废-->
        <el-option label="维护" value='2'></el-option>
        <el-option label="作废" value='3'></el-option>
      </el-select>
      <el-input @keyup.enter.native="handleFilter" style="width: 280px;" class="filter-item" placeholder="输入标识搜索" v-model="search.sign_no"></el-input>
      <el-button class="filter-item" type="primary" plain v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <div style="margin-top: 20px;margin-bottom:10px">
        <el-select  style="width: 140px" class="filter-item" v-model="actionType" placeholder="选择操作方式" >
            <el-option label="选择操作方式" value=''></el-option> 
            <el-option label="删除" value='1'></el-option> 
            <el-option label="下载" value='2'></el-option> 
        </el-select>
        <el-button type="info" v-if="multipleId.length<=0 || this.actionType==''" >确认</el-button>
        <el-button :loading="saveLoading" type="primary" v-else-if="multipleId.length>0 && this.actionType=='2'" @click="handleActionBtn()" v-roles="'downCheckCodeZip'">确认</el-button>
        <el-button :loading="saveLoading" type="primary" v-else @click="handleActionBtn()" v-roles="'delSymbol'">确认</el-button>
    </div>
    <!-- // 这是列表 -->
    <el-table :data="listData" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="index"  align="center" label="序号" width="80"></el-table-column>
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column align="center" label="预览码" width="100">
        <template slot-scope="scope">
           <span><img :src="scope.row.code_url" style="width:80px;height:80px" onerror='this.src="http://wx.qlogo.cn/mmopen/C2rEUskXQiblFYMUl9O0G05Q6pKibg7V1WpHX6CIQaic824apriabJw4r6EWxziaSt5BATrlbx1GVzwW2qjUCqtYpDvIJLjKgP1ug/0"' /></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="唯一识别码">
        <template slot-scope="scope">
          <span>{{scope.row.sign_no}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="房间号">
        <template slot-scope="scope">
          <span>{{scope.row.room_no}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="扫码状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{scope.row.status | statusName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="160px">
        <template slot-scope="scope">
          <span>{{scope.row.created_at}}</span>
        </template>
      </el-table-column>
      <!-- //这里是操作   -->
      <el-table-column align="center" fixed="right" label="操作" width="140" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handlEdit(scope.row)" v-roles="'editDevice'">编辑</el-button>
          <el-button size="mini" type="danger" @click="handlDel(scope.row)" v-roles="'delDevice'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--添加窗口  -->
    <edit-symbol :visible.sync="editVisible" :propsData="propsData" @refresh='isrefresh' ref="triggerWay"></edit-symbol>  
    
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!--可自定义按钮的样式、show/hide临界点、返回的位置  -->
    <!--如需文字提示，可在外部添加element的<el-tooltip></el-tooltip>元素  -->
    <el-tooltip placement="top" content="回到顶部">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>
    
  </div>
</template>
<script>

import editSymbol from '../symbol/editSymbol'
import BackToTop from '@/components/BackToTop' // 回到顶部
import * as api from '@/api/main-api' // API
import waves from '@/directive/waves' // 水波纹指令
import { mapGetters } from 'vuex'

export default {
  name: 'symbolList',
  directives: {
    waves
  },
  components: { BackToTop, editSymbol },
  computed: {
    ...mapGetters(['outlet_id'])
  },
  data() {
    return {
      // 回到顶部样式
      myBackToTopStyle: {
        right: '50px',
        bottom: '50px',
        width: '40px',
        height: '40px',
        'z-index': '9999',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
        background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
      },

      // 长带参数
      listQuery: {
        page: 1,
        pagesize: 50
      },

      // 搜索字段
      search: {
        sign_no: '',
        status: ''
      },
      total: 0,
      listLoading: false,
      listData: [],
      multipleId: [], // 多选
      actionType: '', // -1删除;2 下载
      saveLoading: false,
      // 编辑传值
      editVisible: false,
      propsData: {}
    }
  },

  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'warning',
        3: 'danger'
      }
      return statusMap[status]
    },
    statusName(status) {
      return (status === '1') ? '使用中' : ((status === '2') ? '维护中' : '作废')
    }
  },

  // 初始化数据
  created() {
    this.listQuery.unit_id = this.outlet_id
    setTimeout(() => {
      this.fetchData()
    }, 20)
  },

  // 触动方法
  methods: {
    // 控制每页调数
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.fetchData()
    },

    // 跳页
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },

    // 搜搜
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },

    // 编辑
    handlEdit(row) {
      this.editVisible = !this.editVisible
      this.propsData = row
      this.$refs['triggerWay'].setTitle('编辑扫餐码')
    },

    // 子窗口关闭,刷新数据
    isrefresh(data) {
      this.fetchData()
    },

    // 多选框选择数据
    handleSelectionChange(val) {
      this.multipleId = []
      val.forEach(row => {
        this.multipleId.push(row.id)
      })
    },

    // 按钮操作
    handleActionBtn() {
      if (this.actionType) {
        if (this.actionType === '1') { // 删除
          this.deleteSelect()
        } else {
          this.downCheckCodeZip() // 下载
        }
      }
    },

    // 删除单个
    handlDel(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          id: row.id,
          unit_id: this.outlet_id
        }
        api.delSymbolApi(params).then(response => {
          if (response.data.code === 0) {
            const index = this.listData.indexOf(row)
            this.listData.splice(index, 1)
            this.$root.message('已移除指定二维码', 'success')
            this.total = this.total - 1
          }
        })
      }).catch(() => {
        this.$root.message('已取消删除', 'info')
      })
    },

    // 选择批量删除
    deleteSelect() {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var comments = this.multipleId
        if (comments.length <= 0) {
          this.$root.message('勾选要操作的数据项', 'info')
          return false
        }
        var num = []
        for (let i = 0; i < comments.length; i++) {
          num.push(comments[i])
        }

        var ids = num.join(',')
        var params = {
          id: ids,
          unit_id: this.outlet_id
        }
        api.delSymbolApi(params).then(response => {
          if (response.data.code === 0) {
            for (let j = 0; j < comments.length; j++) {
              this.listData.forEach((item) => {
                // 遍历prodAllPrice这个字段，并累加
                if (item.id === comments[j]) {
                  this.listData.splice(item, 1)
                  this.total = this.total - 1
                }
              })
            }
            this.$root.message('已移除指定二维码', 'success')
          }
        })
      }).catch(() => {
        this.$root.message('已取消删除', 'info')
      })
    },

    // 下载批量二维码,按当前的站点来
    downCheckCodeZip() {
      this.$confirm('确定下载?, 是否继续?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var comments = this.multipleId
        if (comments.length <= 0) {
          this.$root.message('勾选要操作的数据项', 'info')
          return false
        }
        var num = []
        for (let i = 0; i < comments.length; i++) {
          num.push(comments[i])
        }
        var ids = num.join(',')
        var params = {
          id: ids,
          unit_id: this.outlet_id
        }
        // 调用接口
        api.downCheckZipApi(params).then(response => {
          if (response.data.code === 0) {
            var url = response.data.data
            window.location.href = url // 在原标签页打开
            this.$root.message('下载成功', 'success')
          }
        })
      }).catch(() => {
        this.$root.message('已取消下载', 'info')
      })
    },

    // 获取数据
    fetchData() {
      this.listLoading = true
      this.listQuery = Object.assign(this.listQuery, this.search)
      return new Promise((resolve, reject) => {
        api.symbolListApi(this.listQuery).then(response => {
          if (response.data.code === 0) {
            this.listData = response.data.data
            this.total = response.data.total
          }
          this.listLoading = false
        })
      })
    }
  },
  // 监事事件
  watch: {
    outlet_id(id) {
      this.$nextTick(() => {
        setTimeout(() => {
          this.listQuery.unit_id = id
          this.fetchData()
        }, 100)
      })
    }

  }
}
</script>
